<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="handleSearchList()" size="small">
          查询搜索
        </el-button>
        <el-button style="float:right;margin-right: 15px" @click="handleResetSearch()" size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="员工姓名" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加</el-button>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>文件插入</span>
      <input type="file" ref="fileInput" v-on:change="onChange" />
      <el-button size="mini" class="btn-add" @click="handleAddList()" :disabled="!fileState"
        style="margin-left: 20px">全部添加</el-button>
    </el-card>
    <div class="table-container">
      <!-- 展示所有员工列表 -->
      <div v-if="!foundEmployee">
        <el-table ref="adminTable" :data="checkingList" style="width: 100%;" v-loading="listLoading" border>
          <el-table-column label="编号" width="100" align="center">
            <template slot-scope="scope">
              {{ checkingList.length - scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center">
            <template slot-scope="scope">{{ scope.row.employeeName }}</template>
          </el-table-column>
          <el-table-column label="工号 " align="center">
            <template slot-scope="scope">{{ scope.row.employeeId }}</template>
          </el-table-column>
          <el-table-column label="手机号 " align="center">
            <template slot-scope="scope">{{ scope.row.phone }}</template>
          </el-table-column>
          <el-table-column label="员工部门 " align="center">
            <template slot-scope="scope">{{ scope.row.employeeDepartment }}</template>
          </el-table-column>
          <el-table-column label="请假起始时间" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.holidayStart) }}</template>
          </el-table-column>
          <el-table-column label="请假结束时间" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.holidayEnd) }}</template>
          </el-table-column>
          <el-table-column label="请假类型" width="100" align="center">
            <template slot-scope="scope">{{ scope.row.more }}</template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleUpdate(scope.$index, scope.row)">编辑
              </el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 展示找到的员工信息 -->
      <div v-else>
        <h3>找到的考勤信息:</h3>
        <el-table ref="adminTable" :data="checkingListByEmployeeName" style="width: 100%;" v-loading="listLoading"
          border>
          <el-table-column label="编号" width="100" align="center">
            <template slot-scope="scope">
              {{ checkingListByEmployeeName.length - scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center">
            <template slot-scope="scope">{{ scope.row.employeeName }}</template>
          </el-table-column>
          <el-table-column label="工号 " align="center">
            <template slot-scope="scope">{{ scope.row.employeeId }}</template>
          </el-table-column>
          <el-table-column label="手机号 " align="center">
            <template slot-scope="scope">{{ scope.row.phone }}</template>
          </el-table-column>
          <el-table-column label="员工部门 " align="center">
            <template slot-scope="scope">{{ scope.row.employeeDepartment }}</template>
          </el-table-column>
          <el-table-column label="请假起始时间" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.holidayStart) }}</template>
          </el-table-column>
          <el-table-column label="请假结束时间" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.holidayEnd) }}</template>
          </el-table-column>
          <el-table-column label="请假类型" width="100" align="center">
            <template slot-scope="scope">{{ scope.row.more }}</template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleUpdate(scope.$index, scope.row)">编辑
              </el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button @click="clearFoundEmployee">返回列表</el-button>
      </div>
    </div>
    <el-dialog :title="isEdit ? '编辑考勤' : '添加考勤'" :visible.sync="dialogVisible" width="40%">
      <el-form :model="admin" ref="adminForm" label-width="150px" size="small">
        <el-form-item label="姓名：">
          <el-input v-model="admin.employeeName" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="工号：">
          <el-input v-model="admin.employeeId" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input v-model="admin.phone" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="部门：">
          <el-input v-model="admin.employeeDepartment" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="请假起始时间：">
          <input type="date" v-model="admin.holidayStart" placeholder="选择起始时间" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="请假结束时间：">
          <input type="date" v-model="admin.holidayEnd" placeholder="选择结束时间" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="请假类型：">
          <el-input v-model="admin.more" style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { formatDate } from '@/utils/date';
import { read, utils } from 'xlsx';
import { checkingChange, checkingDelete, checkingFind, checkingInsert, checkingInsertList, checkingList } from '../../api/page2';

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  keyword: null
};
const defaultAdmin = {
  id: null,
  username: null,
  password: null,
  nickName: null,
  email: null,
  note: null,
  status: 1
};
export default {
  name: 'checkingList',
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      checkingList: [], // 存储所有考勤列表的数据
      checkingListByEmployeeName: [],
      listLoading: false,
      dialogVisible: false,
      admin: Object.assign({}, defaultAdmin),
      isEdit: false,
      foundEmployee: false,
      fileState: false,
      fileList: [],
      tableHead: [],
      tableDate: []
    }
  },
  created() {
    this.getEmployeeMessage();
  },
  methods: {
    onChange(e) {
      const file = e.target.files[0];
      const fileReader = new FileReader();
      this.fileState = true

      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = read(data, { type: "binary" });
          const params = [];
          workbook.SheetNames.forEach(item => {
            params.push({
              name: item,
              dataList: utils.sheet_to_json(workbook.Sheets[item])
            });
            this.tableDate.push(utils.sheet_to_json(workbook.Sheets[item]))
          })

          // 将params赋值给fileList
          this.fileList = params;

          if (this.tableDate.length > 0) {
            for (const key in this.tableDate[0][0]) {
              this.tableHead.push(key);
            }
          }
          console.log(this.fileList[0].dataList);
          // this.fileState = true
          return params;
        } catch (e) {
          console.log("error:" + e);
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    },
    handleAddList() {
      checkingInsertList(JSON.stringify(this.fileList[0].dataList)).then(data => {
        // 清除文件输入框的值
        this.$refs.fileInput.value = '';
        this.fileList = [];
        this.tableHead = [];
        this.tableDate = [];
        this.fileState = false;
        if (data.state === 200) {
          this.$message({
            message: '添加成功！',
            type: 'success'
          });
        } else {
          this.$message({
            message: data.message,
            type: 'warning'
          });
        }
        this.getEmployeeMessage();
      })
        .catch(error => {
          console.error('Error:', error);
          alert('网络请求失败，请稍后再试');
        })
    },
    formatDateForInput(dateStr) {
      if (!dateStr) return null;
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    formatEmployeeDates(checking) {
      return {
        ...checking,
        holidayStart: this.formatDateForInput(checking.holidayStart),
        holidayEnd: this.formatDateForInput(checking.holidayEnd)
      };
    },
    onWorkDayChange(value) {
      console.log('New work day:', value);
      this.admin.workDay = value;
    },
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toISOString().split('T')[0];
    },
    // 获取数据
    getEmployeeMessage() {
      checkingList().then(data => {
        console.log('Success:', data);
        let dataList = data.data.map(checking => this.formatEmployeeDates(checking));
        this.checkingList = [...dataList].reverse();
      })
        .catch(error => {
          console.error('Error:', error);
          alert('网络请求失败，请稍后再试');
        })
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getCheckingByEmployeeName()
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleAdd() {
      this.admin = {}
      this.dialogVisible = true;
      this.isEdit = false;
      // this.admin = Object.assign({},defaultAdmin);
    },
    // 删除数据
    handleDelete(index, row) {
      this.$confirm('是否要删除该考勤?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        checkingDelete(row.id).then(data => {
          console.log('Success:', data);
          this.getEmployeeMessage();
        })
          .catch(error => {
            console.error('Error:', error);
            alert('网络请求失败，请稍后再试');
          })
      });
    },
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.admin = Object.assign({}, row);
    },
    handleDialogConfirm() {
      this.$confirm('是否要确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.isEdit) {
          const employeeMessage = this.admin // 假设 admin 对象符合 EmployeeMessage 结构

          checkingChange(JSON.stringify(employeeMessage)).then(data => {
            // 假设服务器返回的状态码在 data.code 或 data.state 中
            if (data.state === 200 || data.code === 200) {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getEmployeeMessage(); // 刷新列表
            } else {
              // 如果服务器返回了非成功的状态码，给出相应提示
              this.$message({
                message: `修改失败：${data.message || '未知错误'}`,
                type: 'error'
              });
            }
          })
            .catch(error => {
              console.error('Error:', error);
              this.$message({
                message: '网络请求失败，请稍后再试',
                type: 'error'
              });
            });
        } else {
          checkingInsert(JSON.stringify(this.admin)).then(data => {
            if (data.state === 200) {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getEmployeeMessage();
            }
          })
            .catch(error => {
              console.error('Error:', error);
              alert('网络请求失败，请稍后再试');
            })
        }
      })
    },
    getCheckingByEmployeeName() {
      const employeeName = this.listQuery.keyword
      checkingFind(employeeName).then(data => {
        console.log('Success:', data);
        this.foundEmployee = true
        this.checkingListByEmployeeName = data.data;
        // this.getEmployeeMessage();
      })
        .catch(error => {
          console.error('Error:', error);
          alert('网络请求失败，请稍后再试');
        })
    },
    clearFoundEmployee() {
      this.foundEmployee = false;
    },
  }
}

</script>
<style></style>
